import React, { useRef, useState, useCallback } from 'react'
import './App.new.css'

// 使用组件化的弹幕系统
import { 
  VideoBarrage, 
  useBarrage, 
  createBarrage, 
  getPreset,
  getRandomColor,
  SimpleSettingsButton
} from './components/barrage-component'
// import type { PoseDetectionState } from './components/barrage-component'
import type { BarrageSettings as BarrageSettingsType } from './components/barrage-component/types/settings'

// 视频选择器和设置组件（从barrage-component导入）
import { VideoDrawer, useVideoManager } from './components/barrage-component'


/**
 * 使用组件化弹幕系统的演示应用
 */
export default function App() {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [inputText, setInputText] = useState('')
  // const [queueStatus, setQueueStatus] = useState({ queueLength: 0, activeCount: 0, maxCount: 0 })

  // 弹幕数据状态
  const [allBarrageData, setAllBarrageData] = useState<any[]>([])
  const [barrageData, setBarrageData] = useState<any[]>([])
  const [displayedBarrages, setDisplayedBarrages] = useState<Set<string>>(new Set())
  // const [serverStatus, setServerStatus] = useState<'connected' | 'disconnected' | 'checking'>('checking')
  // const [syncStatus, setSyncStatus] = useState<'synced' | 'syncing' | 'paused'>('synced')
  
  // 保留一些必要的状态
  const [detectionMode] = useState(true) // 🆕 默认启用检测
  const [showSkeleton, setShowSkeleton] = useState(true) // 控制骨架线显示
  // const [poseState, setPoseState] = useState<PoseDetectionState>({
  //   initialized: false,
  //   initializing: false,
  //   modelLoaded: false,
  //   runningMode: 'VIDEO',
  // })

  // 弹幕设置状态
  const [barrageSettings, setBarrageSettings] = useState<BarrageSettingsType | null>(null)

  // 处理弹幕设置变更
  const handleSettingsChange = useCallback((newSettings: any, changedKey?: string) => {
    setBarrageSettings(newSettings)
    
    console.log('🎛️ 弹幕设置已更新:', newSettings)
    
    // 映射设置到弹幕配置
    const barrageConfig: any = {
      fontSize: newSettings.fontSize,
      opacity: newSettings.opacity / 100, // 转换为0-1的小数
      speed: newSettings.speed,
      faceDetection: newSettings.avoidPerson, // 人物防遮盖对应faceDetection
      enabled: newSettings.barrageEnabled, // 弹幕显示开关
      updateExistingBarrages: true, // 🔧 标记需要更新现有弹幕
    }
    
    // 处理显示区域设置
    if (newSettings.displayArea === 'quarter') {
      barrageConfig.trackCount = 3
    } else if (newSettings.displayArea === 'half') {
      barrageConfig.trackCount = 6
    } else if (newSettings.displayArea === 'threequarter') {
      barrageConfig.trackCount = 9
    } else {
      barrageConfig.trackCount = 12
    }
    
    
    // 应用配置到弹幕系统
    try {
      const currentBarrageRef = (window as any).__currentBarrageRef
      if (currentBarrageRef && currentBarrageRef.current && 'updateConfig' in currentBarrageRef.current) {
        (currentBarrageRef.current as any).updateConfig(barrageConfig)
        console.log('✅ 弹幕配置已应用:', barrageConfig)
        
        // 只在弹幕开启且不是弹幕开关变更时发送测试弹幕
        if (newSettings.barrageEnabled && changedKey !== 'barrageEnabled') {
          const testMessages = [
            '设置已更新！',
            '弹幕效果预览',
            '这是测试弹幕',
            '设置生效中...',
            '新配置已应用'
          ]
          const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)]
          
          // 动态获取 addBarrage 函数
          const currentAddBarrage = (window as any).__currentAddBarrage
          if (currentAddBarrage && randomMessage) {
            // 直接传递文本，让 addBarrage 函数处理弹幕创建
            currentAddBarrage(randomMessage)
          }
        }
      } else {
        console.warn('⚠️ 弹幕渲染器未就绪，配置将在下次初始化时应用')
        // 保存配置，等待渲染器就绪后应用
        localStorage.setItem('pending-barrage-config', JSON.stringify(barrageConfig))
      }
    } catch (error) {
      console.error('❌ 应用弹幕配置时出错:', error)
    }
    
    // 显示用户友好的设置信息
    const settingLabels: Record<string, string> = {
      fontSize: '字体大小',
      opacity: '透明度',
      speed: '移动速度',
      avoidPerson: '智能防挡弹幕',
      displayArea: '显示区域',
      density: '弹幕密度',
      mode: '弹幕模式',
      screenScale: '弹幕随屏幕缩放',
      preventBlock: '防挡字幕',
      barrageEnabled: '弹幕显示'
    }
    
    Object.entries(newSettings).forEach(([key, value]) => {
      const label = settingLabels[key] || key
      let displayValue = value
      
      if (key === 'opacity') {
        displayValue = `${value}%`
      } else if (key === 'speed') {
        displayValue = `${value}px/s`
      } else if (key === 'fontSize') {
        displayValue = `${value}px`
      } else if (key === 'avoidPerson') {
        displayValue = value ? '✅ 开启' : '❌ 关闭'
      } else if (key === 'displayArea') {
        const areaLabels = {
          quarter: '1/4区域(3轨道)',
          half: '2/4区域(6轨道)',
          threequarter: '3/4区域(9轨道)',
          fullscreen: '全屏(12轨道)'
        }
        displayValue = areaLabels[value as keyof typeof areaLabels] || value
      } else if (key === 'density') {
        const densityLabels = {
          sparse: '稀疏',
          normal: '正常',
          dense: '密集'
        }
        displayValue = densityLabels[value as keyof typeof densityLabels] || value
      } else if (key === 'mode') {
        const modeLabels = {
          scroll: '滚动',
          fixed: '固定',
          colorful: '彩色',
          advanced: '高级'
        }
        displayValue = modeLabels[value as keyof typeof modeLabels] || value
      } else if (key === 'screenScale' || key === 'preventBlock' || key === 'avoidPerson' || key === 'barrageEnabled') {
        displayValue = value ? '✅ 开启' : '❌ 关闭'
      }
      
      console.log(`  ${label}: ${displayValue}`)
    })
  }, [])

  // 视频管理
  const {
    videos,
    currentVideoId,
    selectVideo,
    uploadVideo,
    refreshVideos
  } = useVideoManager({
    onVideoChange: (video) => {
      // 当视频切换时，更新video元素的src
      if (videoRef.current) {
        videoRef.current.src = video.url
        videoRef.current.load()
      }
      
      // 清空当前弹幕，准备加载新视频的弹幕
      if (barrageRef.current) {
        barrageRef.current.clear()
        
        // 多次强制清理canvas内容，防止动画残留
        if ('clearCanvas' in barrageRef.current) {
          (barrageRef.current as any).clearCanvas()
          // 延迟再次清理，确保彻底清空
          setTimeout(() => {
            if (barrageRef.current && 'clearCanvas' in barrageRef.current) {
              (barrageRef.current as any).clearCanvas()
            }
          }, 50)
        }
      }
      
      // 延迟一下确保视频加载完成后重新设置弹幕区域
            setTimeout(() => {
        if (barrageRef.current && 'setupCanvas' in barrageRef.current) {
          (barrageRef.current as any).setupCanvas()
        }
      }, 100)
      
      // console.log(`切换到视频: ${video.name} (ID: ${video.id})`)
    }
  })

  // 视频抽屉状态
  const [isVideoDrawerOpen, setIsVideoDrawerOpen] = useState(false)
  const [showVideoTest, setShowVideoTest] = useState(false) // 🧪 视频测试页面状态

  // 移除复杂的基准配置逻辑

  // 加载弹幕数据
  React.useEffect(() => {
    const loadBarrages = async () => {
      try {
        // 优先尝试从 json-server 加载数据
        let response
        let data
        
        try {
          response = await fetch('http://localhost:3001/barrages')
          data = await response.json()
          // setServerStatus('connected')
          // console.log('从 JSON Server 加载弹幕数据成功:', data?.length, '条')
        } catch (jsonServerError) {
          // setServerStatus('disconnected')
          // console.warn('JSON Server 不可用，尝试从静态文件加载:', (jsonServerError as Error).message)
          // 回退到静态文件
          response = await fetch('/db.json')
          const staticData = await response.json()
          data = staticData.barrages || []
          // console.log('从静态文件加载弹幕数据成功:', data?.length, '条')
        }
        
        setAllBarrageData(data || [])
      } catch (error) {
        // console.error('加载弹幕数据失败:', error)
        setAllBarrageData([])
        setBarrageData([])
      }
    }
    
    loadBarrages()
  }, [])

  // 根据当前视频ID过滤弹幕数据
  React.useEffect(() => {
    if (allBarrageData.length > 0 && currentVideoId) {
      const filteredBarrages = allBarrageData.filter(barrage => 
        barrage.videoId === currentVideoId
      )
      setBarrageData(filteredBarrages)
      // console.log(`为视频 ${currentVideoId} 加载了 ${filteredBarrages.length} 条弹幕`)
      
      // 清空已显示的弹幕记录，重新开始
      setDisplayedBarrages(new Set())
    } else {
      setBarrageData([])
    }
  }, [allBarrageData, currentVideoId])

  // 监听视频尺寸变化，确保弹幕区域同步
  React.useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const handleVideoResize = () => {
      // 延迟一下确保视频尺寸已经更新
      setTimeout(() => {
        if (barrageRef.current && 'setupCanvas' in barrageRef.current) {
          (barrageRef.current as any).setupCanvas()
          // console.log('视频尺寸变化，重新设置弹幕区域')
        }
      }, 50)
    }

    // 监听多个可能导致视频尺寸变化的事件
    const events = ['loadedmetadata', 'resize', 'loadeddata', 'canplay']
    events.forEach(eventName => {
      video.addEventListener(eventName, handleVideoResize)
    })

    // 监听窗口大小变化
    window.addEventListener('resize', handleVideoResize)

    return () => {
      events.forEach(eventName => {
        video.removeEventListener(eventName, handleVideoResize)
      })
      window.removeEventListener('resize', handleVideoResize)
    }
  }, [videoRef])

  // 使用弹幕Hook
  const {
    barrageRef,
    addBarrage,
    // clearBarrages,
    // activeCount,
    // maxCapacity,
    isFull
  } = useBarrage({
    config: getPreset('default'), // 使用默认配置
    events: {
      // 移除控制台日志输出以提升性能
      // onAdd: (barrage) => console.log('弹幕添加:', barrage.text),
      // onRemove: (barrage) => console.log('弹幕移除:', barrage.text),
      // onCapacityChange: (active, max) => console.log(`容量: ${active}/${max}`),
      // onError: (error) => console.error('弹幕错误:', error)
    }
  })

  // 当弹幕系统初始化后，应用待处理的配置
  React.useEffect(() => {
    // 设置全局引用，供设置函数使用
    ;(window as any).__currentBarrageRef = barrageRef
    ;(window as any).__currentAddBarrage = addBarrage
    
    if (barrageRef && barrageRef.current && 'updateConfig' in barrageRef.current) {
      try {
        const pendingConfig = localStorage.getItem('pending-barrage-config')
        if (pendingConfig) {
          const config = JSON.parse(pendingConfig)
          ;(barrageRef.current as any).updateConfig(config)
          localStorage.removeItem('pending-barrage-config')
          console.log('✅ 应用了待处理的弹幕配置:', config)
        }
      } catch (error) {
        console.error('❌ 应用待处理配置时出错:', error)
      }
    }
  }, [barrageRef, addBarrage])

  // 🔬 压力测试：生成1000条弹幕
  const handleStressTest = useCallback(() => {
    if (!videoRef.current) return
    
    // console.log('🔬 开始压力测试：生成 1000 条弹幕...')
    const videoDuration = videoRef.current.duration || 24.71
    const testBarrages: any[] = []
    
    // 生成1000条弹幕
    for (let i = 0; i < 1000; i++) {
      const time = Math.random() * videoDuration
      const barrage = createBarrage(`压力测试弹幕 ${i + 1}`, {
        color: getRandomColor(),
        fontSize: 20,
        user: `测试用户${i + 1}`
      })
      testBarrages.push({
        barrage,
        time,
        videoId: currentVideoId,
        id: `stress-test-${i}`,
        text: `压力测试弹幕 ${i + 1}`,
        timestamp: new Date().toISOString()
      })
    }
    
    // 添加到弹幕数据中
    setAllBarrageData(prev => [...prev, ...testBarrages])
    setBarrageData(prev => [...prev, ...testBarrages])
    
    // console.log(`✅ 压力测试弹幕生成完成：共 ${testBarrages.length} 条`)
    // console.log(`📊 当前视频弹幕总数：${barrageData.length + 1000} 条`)
    // 压力测试弹幕生成
  }, [videoRef, currentVideoId, barrageData.length])


  // 🔄 同步弹幕列表
  // 移除复杂的随屏幕缩放功能（简化版本不包含此功能）

  // 发送弹幕
  const handleSendBarrage = async () => {
    if (!inputText.trim() || isFull) return

    const barrageData = {
      text: inputText,
      color: getRandomColor(),
      time: videoRef.current?.currentTime || 0,
      type: 'scroll',
      fontSize: 20,
      user: '用户' + Math.floor(Math.random() * 1000),
      timestamp: new Date().toISOString()
    }
    
    // 先添加到本地显示
    const barrage = createBarrage(barrageData.text, {
      color: barrageData.color,
      fontSize: barrageData.fontSize,
      user: barrageData.user
    })
    addBarrage(barrage)
    
    // 尝试发送到服务器
    try {
      const response = await fetch('http://localhost:3001/barrages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(barrageData)
      })
      
      if (response.ok) {
        // console.log('弹幕发送到服务器成功')
      } else {
        // console.warn('弹幕发送到服务器失败:', response.statusText)
      }
    } catch (error) {
      // console.warn('无法连接到服务器，弹幕仅本地显示:', (error as Error).message)
    }
    
    setInputText('')
  }




  // 切换检测模式
  // const toggleDetectionMode = () => {
  //   const newMode = !detectionMode
  //   setDetectionMode(newMode)
  //   
  //   // 通过 barrageRef 更新配置
  //   if (barrageRef.current && 'updateConfig' in barrageRef.current) {
  //     (barrageRef.current as any).updateConfig({ faceDetection: newMode })
  //   }

  //   if (!newMode) {
  //     setPoseState({
  //       initialized: false,
  //       initializing: false,
  //       modelLoaded: false,
  //       runningMode: 'VIDEO',
  //       error: undefined,
  //     })
  //   }
  // }


  // const syncPoseDetectionState = useCallback(() => {
  //   if (barrageRef.current && 'getPoseDetectionState' in barrageRef.current) {
  //     const state = (barrageRef.current as any).getPoseDetectionState?.()
  //     if (state) {
  //       setPoseState(state)
  //     }
  //   }
  // }, [])

  // React.useEffect(() => {
  //   const id = window.setInterval(() => {
  //     syncPoseDetectionState()
  //   }, 500)

  //   return () => window.clearInterval(id)
  // }, [syncPoseDetectionState])

  // 同步骨架显示状态（简化版本）
  React.useEffect(() => {
    barrageRef.current?.updateConfig({ showSkeleton })
  }, [showSkeleton])

  // 定期更新队列状态
  React.useEffect(() => {
    const updateQueueStatus = () => {
      if (barrageRef.current && 'getQueueStatus' in barrageRef.current) {
        // const status = (barrageRef.current as any).getQueueStatus()
        // setQueueStatus(status)
      }
    }

    const interval = setInterval(updateQueueStatus, 1000) // 每秒更新一次
    return () => clearInterval(interval)
  }, [])

  // 弹幕与视频时间同步
  const syncBarrageWithVideo = () => {
    const video = videoRef.current
    if (!video || barrageData.length === 0) return

    // setSyncStatus('syncing')
    const currentTime = video.currentTime
    
    // 清除当前弹幕和已显示记录
    barrageRef.current?.clear()
    setDisplayedBarrages(new Set())
    
    // 标记所有早于当前时间的弹幕为已显示（避免它们重复出现）
    const pastBarrages = barrageData.filter(barrage => barrage.time < currentTime - 1)
    const pastIds = new Set(pastBarrages.map(b => b.id))
    setDisplayedBarrages(pastIds)
    
    // console.log(`🔄 弹幕同步到 ${currentTime.toFixed(1)}s，跳过 ${pastBarrages.length} 条过去的弹幕`)
    
    // 短暂延迟后标记为已同步
    setTimeout(() => {
      // setSyncStatus('synced')
    }, 300)
  }


  // 🆕 创建 displayedBarrages 的 ref，避免闭包问题
  const displayedBarragesRef = useRef(displayedBarrages)
  displayedBarragesRef.current = displayedBarrages

  // 视频时间监听 - 自动显示弹幕
  React.useEffect(() => {
    const video = videoRef.current
    if (!video || barrageData.length === 0) return

    const handleTimeUpdate = () => {
      const currentTime = video.currentTime
      
      // 查找当前时间应该显示的弹幕
      const currentBarrages = barrageData.filter(barrage => {
        const timeDiff = Math.abs(barrage.time - currentTime)
        const isInTimeRange = timeDiff < 0.5 // 0.5秒的容差
        const notDisplayed = !displayedBarragesRef.current.has(barrage.id)
        return isInTimeRange && notDisplayed
      })

      // 添加匹配的弹幕
      currentBarrages.forEach(barrageItem => {
        const barrage = createBarrage(barrageItem.text, {
          color: barrageItem.color,
          fontSize: barrageItem.fontSize || 20
        })
        addBarrage(barrage)
        
        // 标记为已显示，避免重复显示
        setDisplayedBarrages(prev => new Set([...prev, barrageItem.id]))
      })
    }

    video.addEventListener('timeupdate', handleTimeUpdate)
    
    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate)
    }
    // 🆕 只依赖 barrageData 和 addBarrage，配置变化不会重新绑定事件
  }, [barrageData, addBarrage])


  // 视频播放状态同步
  React.useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const handlePlay = () => {
      // 恢复弹幕播放
      barrageRef.current?.resume()
      // setSyncStatus('synced')
      // console.log('🎬 视频播放，弹幕恢复')
      
      // 添加欢迎弹幕（仅在视频开始时）
      if (video.currentTime < 1) {
        setTimeout(() => {
          addBarrage(createBarrage('🎬 视频开始播放！', { color: '#FFD700', fontSize: 24 }))
        }, 500)
        
      setTimeout(() => {
          addBarrage(createBarrage('欢迎观看！可以发送弹幕互动哦 💬', { color: '#4ECDC4' }))
        }, 2000)
      }
    }

    const handlePause = () => {
      // 暂停弹幕
      barrageRef.current?.pause()
      // setSyncStatus('paused')
      // console.log('⏸️ 视频暂停，弹幕暂停')
    }

    const handleSeeked = () => {
      // 视频跳转时，智能同步弹幕
      syncBarrageWithVideo()
      
      // 如果视频正在播放，确保弹幕也继续播放
      if (!video.paused) {
        barrageRef.current?.resume()
      } else {
        barrageRef.current?.pause()
      }
    }

    const handleRateChange = () => {
      // 视频播放速度变化时的处理
      // console.log(`⚡ 视频播放速度变为 ${video.playbackRate}x`)
      
      // 弹幕速度会在renderFrame中自动跟随视频播放速度
    }

    video.addEventListener('play', handlePlay)
    video.addEventListener('pause', handlePause)
    video.addEventListener('seeked', handleSeeked)
    video.addEventListener('ratechange', handleRateChange)
    
    return () => {
      video.removeEventListener('play', handlePlay)
      video.removeEventListener('pause', handlePause)
      video.removeEventListener('seeked', handleSeeked)
      video.removeEventListener('ratechange', handleRateChange)
    }
  }, [addBarrage, barrageRef])

  return (
    <div className="app">
      
      {/* 视频容器 */}
      <div className="video-container" style={{ position: 'relative', width: '100%', height: '600px' }}>
        <video
          ref={videoRef}
          src="/demo-video.mp4"
          controls
          className="video-player"
          style={{ width: '100%', height: '100%', objectFit: 'contain' }}
        />
        
        {/* 弹幕组件 */}
        <div style={{ 
          display: barrageSettings?.barrageEnabled === false ? 'none' : 'block',
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none'
        }}>
          <VideoBarrage
            ref={barrageRef}
            videoRef={videoRef}
            config={getPreset('default')}
            enabled={true}
          />
        </div>
      </div>
      
      {/* 控制面板 */}
      <div className="controls">

        {/* 弹幕输入 */}
        <div className="input-section">
          <input
            type="text"
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSendBarrage()}
            placeholder="输入弹幕内容..."
            className="barrage-input"
            disabled={isFull}
          />
          <button 
            onClick={handleSendBarrage} 
            className="send-btn"
            disabled={!inputText.trim() || isFull}
          >
            发送
          </button>
        </div>
        
        {/* 控制按钮 */}
        <div className="control-buttons">
          <button 
            onClick={() => setShowSkeleton(!showSkeleton)}
            className={showSkeleton ? 'active' : ''}
            disabled={!detectionMode}
            title={showSkeleton ? '隐藏骨架线' : '显示骨架线'}
          >
            {showSkeleton ? '🦴 骨架显示' : '🦴 骨架隐藏'}
          </button>
          <button onClick={() => setIsVideoDrawerOpen(true)} style={{backgroundColor: '#28a745', marginLeft: '10px'}}>
            📁 Videos
          </button>
          
          {/* 弹幕设置组件 */}
          <div style={{ marginLeft: '10px' }}>
            <SimpleSettingsButton onSettingsChange={handleSettingsChange} />
          </div>
          
          <button 
            onClick={handleStressTest} 
            style={{backgroundColor: '#dc3545', color: 'white', marginLeft: '10px'}}
            title="生成1000条弹幕进行压力测试"
          >
            🔬 压力测试 (1000条)
          </button>
        </div>
      </div>
      
      {/* 视频抽屉 */}
      <VideoDrawer
        videos={videos}
        currentVideoId={currentVideoId}
        onVideoSelect={selectVideo}
        onVideoUpload={async (file) => {
          try {
            await uploadVideo(file)
            // console.log('视频上传成功:', file.name)
          } catch (error) {
            // console.error('视频上传失败:', error)
            alert(`视频上传失败: ${error instanceof Error ? error.message : '未知错误'}`)
          }
        }}
        onRefresh={refreshVideos}
        isOpen={isVideoDrawerOpen}
        onClose={() => setIsVideoDrawerOpen(false)}
      />

      {/* 🧪 视频检测测试页面 */}
      {showVideoTest && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'white',
          zIndex: 10000,
          overflow: 'auto'
        }}>
          <div style={{
            position: 'absolute',
            top: '10px',
            right: '10px',
            zIndex: 10001
          }}>
            <button
              onClick={() => setShowVideoTest(false)}
              style={{
                padding: '10px 15px',
                backgroundColor: '#dc3545',
                color: 'white',
                border: 'none',
                borderRadius: '5px',
                cursor: 'pointer',
                fontSize: '16px'
              }}
            >
              ✕ 关闭测试
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
